<?php

class AuthController extends Zend_Controller_Action{
	
	function init(){
		$this->view->title = 'Login';
		$this->initView();
		$this->view->baseUrl = $this->_request->getBaseUrl();
	}

	/*function indexAction(){
		//$this->_redirect('/');
	}*/

	function loginAction(){
		$this->view->message = '';
		if ($this->_request->isPost()) {

			// collect the data from the user
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$filter = new Zend_Filter_StripTags();
			$usuario = $filter->filter($this->_request->getPost('usuario'));
			$senha = $filter->filter($this->_request->getPost('senha'));

			if (empty($usuario)) {
				$this->view->message = 'Favor entrar com um login.';
			} else {
				// setup Zend_Auth adapter for a database table
				Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
				$db = Zend_Registry::get('db');
				$authAdapter = new Zend_Auth_Adapter_DbTable($db);
				$authAdapter->setTableName('usuarios');
				$authAdapter->setIdentityColumn('usuario');
				$authAdapter->setCredentialColumn('senha');

				// Set the input credential values to authenticate against
				$authAdapter->setIdentity($usuario);
				$authAdapter->setCredential($senha);

				// do the authentication
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				if ($result->isValid()) {
					// success : store database row to auth's storage system
					// (not the password though!)
					$data = $authAdapter->getResultRowObject(null, 'senha');
					$auth->getStorage()->write($data);
					$this->_redirect('/');
				} else {
					// failure: clear database row from session
					$this->view->message = 'Login falhou.';
				}
			}
		}

		$this->view->title = "Login";
		$this->view->buttonText = 'enviar';
		$this->render();
	}

	/*function logoutAction(){
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('/');
	}*/
}
?>